const util = {}


util.version = "1.0.0";

const  phonePattern =  /^1[3456789][0-9]{9}$/;
util.checkPhone = phone=>{
  return phonePattern.test(phone);
}

const tip = (title, icon = 'none', duration = 2000, success= ()=>{})=>{
  wx.showToast({
    title,
    icon,
    duration,
    success
  })
}
util.tip = tip;

const ajax = (url, config = {})=>{
  return new Promise((resolve, reject) => {
    config.name = url;
    config.success = ({result})=>{
      resolve(result); 
    };
    config.fail = error => {
      tip("服务器连接有问题，请稍后再试");
      reject(error);
    }
    wx.cloud.callFunction(config)
  })
}
util.ajax = ajax

function debounce(method, delay) {
  let timer = null;
  return function () {
    let self = this,
      args = arguments;
    timer && clearTimeout(timer);
    timer = setTimeout(function () {
      method.apply(self, args);
    }, delay);
  }
}

util.formatTime = (timestamp, format = "yyyy-MM-dd hh:mm:ss") => {
  if (!timestamp) {
    return "";
  }
  let d;
  if (timestamp instanceof Date) {
    d = timestamp;
  } else {
    d = timestamp ? new Date(timestamp * 1000) : new Date();
  }
  let date = {
    "M+": d.getMonth() + 1,
    "d+": d.getDate(),
    "h+": d.getHours(),
    "m+": d.getMinutes(),
    "s+": d.getSeconds(),
    "q+": Math.floor((d.getMonth() + 3) / 3),
    "S+": d.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
        date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}

util.generateMixed = n => {
  var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  var res = "";
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35);
    res += chars[id];
  }
  return res;
}

module.exports =  util;
